import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/company_info_entity.dart';
import 'package:nyh_motorcade_app/event/update_message_state_event.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/utils/event_bus_utils.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';

class AccountAmountRemindController extends GetxController {
  MultiState multiState = MultiState.loading;

  CompanyInfoEntity? companyInfoEntity;
  double totalAmount = 0.0;
  double companyAmount = 0.0;
  double motorcadeAmount = 0.0;
  double cardAmount = 0.0;

  //是否更新未读消息状态
  bool isUpdateMessageState = false;
  String messageId = "";

  @override
  void onReady() {
    super.onReady();
    dynamic arguments = Get.arguments;
    if (arguments != null && arguments is Map) {
      isUpdateMessageState = arguments[Constant.PARAM_IS_UPDATE_MESSAGE_STATE] ?? false;
      if (isUpdateMessageState) {
        messageId = arguments[Constant.PARAM_MESSAGE_ID] ?? "";
      }
    }
    getCompanyInfo();
  }

  void onRetry() {
    multiState = MultiState.loading;
    update();
    getCompanyInfo();
  }

  Future<void> getCompanyInfo() async {
    httpManager.post(
      Get.context,
      HttpAddress.GET_COMPANY_INFO,
      {"superId": await SPUtils.getString(SPUtils.COMPANY_ID)},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          multiState = MultiState.fail;
          update();
          return;
        }
        companyInfoEntity = CompanyInfoEntity().fromJson(data);
        totalAmount = companyInfoEntity!.totalAmount ?? 0.0;
        List<CompanyInfoAmountDetail> amountDetailList = companyInfoEntity!.amountDetail ?? [];
        if (amountDetailList.isNotEmpty) {
          amountDetailList.forEach((element) {
            switch (element.type ?? "") {
              case "COMPANY":
                companyAmount = element.amount ?? 0.0;
                break;
              case "MOTORCADE":
                motorcadeAmount = element.amount ?? 0.0;
                break;
              case "CARD":
                cardAmount = element.amount ?? 0.0;
                break;
              default:
            }
          });
        }
        multiState = MultiState.success;
        update();

        if (isUpdateMessageState) {
          EventBusUtils.fire(UpdateMessageState(messageId));
        }
      },
      onFail: (code, msg) {
        multiState = MultiState.fail;
        update();
      },
      onError: (msg) {
        multiState = MultiState.error;
        update();
      },
    );
  }
}
